// component/get-coupon/index.js
const common = require('../../public.js');
Component({
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  /**
   * 组件的属性列表
   */
  properties: {
    /** 券的id */
    activId: {
      type: String,
      value: ''
    },
    /** 券的type 4：审核券(资格券)，5:抢券 6：预约券 */
    coupType: {
      type: String,
      value: null
    },
    /** 券编号 */
    cid: {
      type: String,
      value: null
    },
    /** 券类型，1为平台券，2为惠民券 */
    type: {
      type: String,
      value: ''
    },
    /** 标记是否为助力券，1为助力券 */
    help: {
      type: String,
      value: '0'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    showDialog: false,
    base64Code: '',
    code: '',
    captchaId: 'fb6455d8a495496f8780b3c0aed5ea85',
    flag: 1 //1是网易盾 2原来的 
  },

  /**
   * 组件的方法列表
   */
  methods: {
    getCoupon(e) {
      console.log(e, "eeeeeeeeeeeeeeeeee")
      const that = this
      common.getLocalUserInfo(function (success, data) {
        if (success) {
          that.data.userId = data.user.id
          that.data.token = data.token
          // console.log(that.data.coupType, "券的类型")
          if (that.data.coupType == 6) {
            // console.log(that.data.activId,"uuuuuu")
            wx.navigateTo({
              url: `/packageC/pages/coups/signUp?activId=${that.data.activId}`,
            })
            return
          }
          if (that.data.type == 1) {
            console.log(that.data.type, "that.data.type 1111111111")
            // 平台券
            console.log("平台88888")
            that.getAdminCoupons()
          } else if (that.data.type == 2) {
            // 惠民券
            console.log("惠民卷")
            console.log(that.data.type, "that.data.type 222222222")
            that.getCultureCoupons()
          }
        } else {
          that.setData({
            showFullLoading: false
          })
        }
      }, true)
    },
    /**
     * 提交领取
     */
    commit() {
      if (this.data.type == 1) {
        console.log("测试数据66666")
        this.commitAdminCode() //平台
      } else if (this.data.type == 2) {
        console.log("强惠民券")
        this.commitCode() //惠民券
      }
    },
    /**
     * 领取惠民券，弹出验证码对话框
     */
    getCultureCoupons() {
      var that = this
      // if (that.data.flag == 1) {
      //     console.log("login_normol")
      //     // that.selectComponent('#captcha').popup()
      //     // 提交
      //     that.commit()
      //     return
      // }
      this.setData({
        showDialog: true,
        base64Code: ''
      }, function () {
        that.createCultureCouponsCode()
      })
    },
    // 验证码验证结果回调
    handlerVerify_normal: function (ev) {
      var that = this
      console.log('ev:', ev)
      if (!ev.detail[0]) {
        // 验证成功
        console.log('validate:', ev.detail[1])
        that.setData({
          code: ev.detail[1]
        }, _ => {
          //   that.commit()
        })
      } else {
        // 验证失败
        wx.showToast({
          title: '验证失败',
          icon: 'success',
          duration: 2000
        })
      }
    },
    createCultureCouponsCode() {
      const that = this
      common.post('/cityDisCoupon/getMsgValidateCode', '', function (res) {
        if (res.status === 200) {
          that.setData({
            base64Code: res.data.base64Code,
            uuid: res.data.uuid
          })
        } else {
          common.showRequestErrMsg(res)
        }
      })
    },
    getAdminCoupons(e) { // 立刻领取
      const that = this
      this.setData({
        showDialog: true
      }, _ => {
        if (that.data.flag == 1) {
          // console.log("login_normol")
          //   that.selectComponent('#captcha').popup()
          // 验证码
          that.createCode()
          // that.commit()
          return
        }
        // that.createCode()
      })
    },
    // 黄色线上
    commitCode() { // 领取惠民券
      let that = this
      console.log("领取")
      if (this.data.code === null || this.data.code === undefined || this.data.code == '') {
        common.showToast('请输入验证码')
        return
      }
      this.setData({
        showFullLoading: true
      })
      console.log("下一步")
      getApp().getLocation(function (data) {
        const xpoint = data.longitude
        const ypoint = data.latitude
        let tempJson = {
          userId: that.data.userId,
          token: that.data.token,
          dcId: that.data.cid,
          uuid: that.data.uuid,
          validateCode: that.data.code,
          xpoint,
          ypoint,
          helpFlag: that.data.help
        }

        // if (that.data.flag == 1) {
        //     // 网易盾
        //     var urlss = '/cityDisCoupon/receiveCityDiscountCouponByNetEasy'
        // } else if (that.data.flag == 2) {
        //     // 正常
        //     var urlss = '/cityDisCoupon/receiveCityDiscountCouponByCode'
        // }

        var urlss = '/cityDisCoupon/receiveCityDiscountCouponByCode'
        common.post(urlss, tempJson, function (res) {
          if (res.status == 200) {
            common.showToast('领取成功', 'success')
            that.setData({
              code: ''
            })
            that.triggerEvent('completion', {
              couponNo: res.data ? res.data : null,
              type: 1
            })
          } else {
            common.showRequestErrMsg(res)
          }
        }, function () {
          if (that.data.flag == 1) {
            // that.selectComponent('#captcha').reset() //重置验证码
            console.log("重置啦啦啦啦啦")
          }
          console.log("重65566666666")
          that.setData({
            showFullLoading: false
          })
        })
      })
    },
    commitAdminCode() { // 领平台券
        const that = this
        // console.log('--++--',that.data.coupType);
        // common.showToast('领取成功', 'success')
        // that.triggerEvent('completion', ({
        //     type: that.data.coupType==4?2:'',
        //   }))
        // return;
  
      if (that.data.code.toLowerCase() !== that.data.imgCode.toLowerCase()) {
        common.showToast('验证码错误')
        return
      }
      if (that.data.flag == 1) {
        that.setData({
          showFullLoading: true
        })
        // common.showToast()
        getApp().getLocation(function (data) {
          const xpoint = data.longitude
          const ypoint = data.latitude
          let tempJson = {
            userId: that.data.userId,
            token: that.data.token,
            couponId: that.data.cid,
            validateCode: that.data.code,
            xpoint,
            ypoint,
          }
          common.post('/discountCoupon/getCouponByUserNetEasyValidate', tempJson, function (res) {
            //  common.post('/discountCoupon/receiveCityDiscountCouponByCode', tempJson, function (res) {
            if (res.status == 200) {
              common.showToast('领取成功', 'success')
              that.triggerEvent('completion', ({
                type: that.data.coupType==4?2:'',// 4(审核券)资格券  
              }))
            } else {
              common.showRequestErrMsg(res)
            }
          }, function () {
            // that.selectComponent('#captcha').reset()
            that.setData({
              showFullLoading: false
            })

          })
        }, () => {
          console.log("失败了")
        })
        return
      }

      that.validate().then(function () {
        that.setData({
          showFullLoading: true
        })
        getApp().getLocation(function (data) {
          console.log('getLocation信息为==', data);
          const xpoint = data.longitude
          const ypoint = data.latitude
          let tempJson = {
            userId: that.data.userId,
            token: that.data.token,
            couponId: that.data.cid,
            xpoint,
            ypoint,
          }
          common.post('/discountCoupon/getCouponByUser', tempJson, function (res) {
            if (res.status == 200) {
              common.showToast('领取成功', 'success')
              that.triggerEvent('completion')
            } else {
              common.showRequestErrMsg(res)
            }
          }, function () {

            that.setData({
              showFullLoading: false
            })
          })
        })
        // let tempJson = {
        //   userId: that.data.userId,
        //   token: that.data.token,
        //   couponId: that.data.cid
        // }
        // common.post('/discountCoupon/getCouponByUser', tempJson, function (res) {
        //   if (res.status == 200) {
        //     common.showToast('领取成功', 'success')
        //     that.triggerEvent('completion')
        //   } else {
        //     common.showRequestErrMsg(res)
        //   }
        // }, function () {
        //   that.setData({
        //     showFullLoading: false
        //   })
        // })
      })
    },
    closeDialog() {
      this.setData({
        code: ''
      })
    },
    clickCode() { //点击验证码图片更换验证码
      this.createCode()
    },
    createCode() {
      const that = this
      let code = ''
      var codeLength = 4; //验证码的长度  
      var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
        'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); //随机数  
      for (var i = 0; i < codeLength; i++) { //循环操作  
        var index = Math.floor(Math.random() * 36); //取得随机数的索引（0~35）  
        code += random[index]; //根据索引取得随机数加到code上  
      }
      that.setData({
        imgCode: code
      })
    },
    validate() {
      const that = this
      const inputCode = this.data.code ? this.data.code.toUpperCase() : '' //取得输入的验证码并转化为大写     
      return new Promise((resolve, reject) => {
        if (inputCode.length <= 0) { //若输入的验证码长度为0  
          common.showToast('请输入验证码')
          that.setData({
            code: ''
          }, function () {
            // that.createCode()
          })
          reject()
        } else if (inputCode != that.data.imgCode) { //若输入的验证码与产生的验证码不一致时  
          common.showToast('验证码错误')
          that.setData({
            code: ''
          }, _ => {
            that.createCode()
          })
          reject()
        } else { //输入正确时  
          resolve()
        }
      })
    },
  }
})